package com.study.book.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.study.book.common.AuthenticationRequired;
import com.study.book.common.R;
import com.study.book.mapper.AdminMapper;
import com.study.book.pojo.Comment;
import com.study.book.pojo.Forum;
import com.study.book.service.AdminService;
import com.study.book.service.CommentService;
import com.study.book.service.ForumService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(tags = "论坛接口")
@RestController
@RequestMapping("/app/forum")
public class ForumController {

    @Resource
    private ForumService forumService;

    @Resource
    private CommentService commentService;

    @Autowired
    private AdminMapper adminMapper;

    @ApiOperation("获取论坛列表")
    @GetMapping("/list")
    public R<List<Forum>> list() {
        return R.ok(forumService.list());
    }

    @ApiOperation("获取论坛详细内容")
    @GetMapping("/comment/{id}")
    public R<List<Comment>> comment(@PathVariable("id") int forumId) {

        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Comment::getForumid,forumId).orderByDesc(Comment::getSort);
        List<Comment> list = commentService.list(lambdaQueryWrapper);
        list.replaceAll(e->{e.setAdminName(adminMapper.selectById(e.getAdminid()).getUsername());return e;});
        return R.ok(list);
    }

    @ApiOperation("用户发表评论")
    @PostMapping("/addComment")
    @AuthenticationRequired(value = "0")
    public R<Comment> Addcomment(HttpServletRequest request, @RequestBody Comment comment) {
        String id = (String) request.getAttribute("userId");
        comment.setAdminid(Integer.parseInt(id));
      R addcomment =  commentService.Addcomment(comment);
        return addcomment;

    }
}
